package com.loveling.util;

import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: liangjiefa
 * Date: 2017/6/8 23:16
 * To change this template use File | Settings | File Templates.
 */
public class FileUtil {

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        System.out.println("删除文件========" + dir.getName());
        System.out.println("文件路径为========" + dir.getAbsolutePath());
        return dir.delete();
    }


    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param folderPath
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    public boolean deleteDir(String folderPath) {
        boolean flag = false;
        int count = 0;
        File file = new File(folderPath);
        String[] fileList = file.list();
        for (int i = 0; i < fileList.length; i++) {
            flag = deleteDir(new File(file, fileList[i]));
            count++;
        }
        System.out.println("删除" + count + "文件");
        return flag;
    }


    public static void main(String args[]) {
        FileUtil fileUtil = new FileUtil();
        fileUtil.deleteDir("L:\\1023");
    }
}

